package de.htwg_konstanz.ebus.framework.view;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oreilly.servlet.MultipartRequest;

import de.htwg_konstanz.ebus.framework.impEx.IImporter;
import de.htwg_konstanz.ebus.framework.impEx.XmlImporter;

public class ImportAction implements IAction {
	public static final String ACTION_IMPORT = "import";
		
	public boolean accepts(String actionName) {
		return actionName.equalsIgnoreCase(ACTION_IMPORT);
	}

	public String execute(HttpServletRequest request, HttpServletResponse response, ArrayList<String> errorList) {
		MultipartRequest multipartRequest = null;
		try {
			multipartRequest = new MultipartRequest(request, "resources/upload");
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		String fileName = null;
		Enumeration<String> fileNames = multipartRequest.getFileNames();
		if (fileNames.hasMoreElements()) {
			String name = (String) fileNames.nextElement();
			fileName = "resources/upload/" + multipartRequest.getFilesystemName(name);
		}
		
		IImporter importer = new XmlImporter(
					"resources/import/bmecat_new_catalog_1_2_simple_without_NS.xsd",
					fileName);

		System.out.println("Validation: " + importer.isValid());
		if (importer.isValid()) {
			importer.performImport();
		}
		
		ImpExStatusModel importStatus = importer.getStatusModel();
		request.getSession(true).setAttribute("importStatus", importStatus);
		
		
		//delete uploaded file
		File file = new File(fileName);
		file.delete();
		
		return "importResult.jsp";
	}

}
